import { showMySecond } from "@/api/index";
interface IdleItem {
  id: number;
  status: "published" | "check" | "banned" | "sold";
  postTime: string;
  category: string;
  content: string;
  images: string[];
  price: number;
  violationReason?: string;
}

Page({
  data: {
    activeTab: 0,
    isSaving: false,
    themeColor: "#19be6b",

    onSaleList: [] as IdleItem[],
    offShelfList: [] as IdleItem[],
    violationList: [] as IdleItem[],
    checkList: [] as IdleItem[],
    onSaleCount: 0,
    offShelfCount: 0,
    violationCount: 0,

    showEditPopup: false,
    editingItem: null as IdleItem | null,
    editingItemIsOnSale: false, // 新增：用于控制 switch 的状态
    originalItemInfo: {
      index: -1,
      listType: "" as "onSale" | "offShelf" | "violation" | "",
    },
  },

  onLoad() {
    this.fetchData();
  },

  async fetchData() {
    const data = await showMySecond();
		data.forEach(element => {
			element.dateTime = new Date(element.createdAt).toLocaleString()
		});
    const onSaleList = data.filter((item) => item.status === "published");
    const offShelfList = data.filter((item) => item.status === "sold");
    const violationList = data.filter((item) => item.status === "banned");
    const checkList = data.filter((item) => item.status === "check");

    this.setData({
      onSaleList,
      checkList,
      offShelfList,
      violationList,
      onSaleCount: onSaleList.length,
      offShelfCount: offShelfList.length,
      violationCount: violationList.length,
      checkListCount: checkList.length,
    });
  },

  onTabChange(event: WechatMiniprogram.CustomEvent) {
    this.setData({ activeTab: event.detail.value });
  },

  onEditTap(event: WechatMiniprogram.CustomEvent) {
    const { item, index, listType } = event.currentTarget.dataset;
    this.setData({
      editingItem: JSON.parse(JSON.stringify(item)),
      originalItemInfo: { index, listType },
      // 根据当前物品状态，设置 switch 的初始 checked 值
      editingItemIsOnSale: item.status === "published",
      showEditPopup: true,
    });
  },

  onClosePopup() {
    this.setData({ showEditPopup: false, editingItem: null });
  },

  onEditContentChange(event: WechatMiniprogram.CustomEvent) {
    this.setData({ "editingItem.content": event.detail });
  },
  onEditPriceChange(event: WechatMiniprogram.CustomEvent) {
    this.setData({ "editingItem.price": event.detail });
  },

  /**
   * 处理 Switch 状态变化
   */
  onStatusSwitchChange(event: WechatMiniprogram.CustomEvent) {
    const isOnSale = event.detail.value;
    this.setData({
      "editingItem.status": isOnSale ? "on-sale" : "off-shelf",
      editingItemIsOnSale: isOnSale,
    });
  },

  handleConfirmEdit() {
    if (this.data.isSaving) return;
    const { editingItem } = this.data;
    if (!editingItem) return;

    if (!editingItem.content.trim()) {
      return wx.showToast({ title: "宝贝描述不能为空", icon: "none" });
    }
    const price = Number(editingItem.price);
    if (isNaN(price) || price <= 0) {
      return wx.showToast({ title: "请输入有效的价格", icon: "none" });
    }

    this.setData({ isSaving: true });

    setTimeout(() => {
      this.updateLocalData(editingItem);
      this.setData({ isSaving: false, showEditPopup: false });
      wx.showToast({ title: "修改成功", icon: "none" });
    }, 800);
  },

  updateLocalData(updatedItem: IdleItem) {
    const { index, listType } = this.data.originalItemInfo;
    const originalList = this.data[`${listType}List`];
    const originalStatus = originalList[index].status;

    if (updatedItem.status !== originalStatus) {
      const sourceListName = `${listType}List` as
        | "onSaleList"
        | "offShelfList"
        | "violationList";
      const sourceList = [...this.data[sourceListName]];
      sourceList.splice(index, 1);

      const targetListNameKey =
        updatedItem.status === "on-sale" ? "onSaleList" : "offShelfList";
      const targetList = [...this.data[targetListNameKey]];
      if (listType === "violation" && updatedItem.status !== "violation") {
        delete updatedItem.violationReason;
      }
      targetList.unshift(updatedItem);

      this.setData(
        {
          [sourceListName]: sourceList,
          [targetListNameKey]: targetList,
        },
        () => {
          this.recalculateCounts();
        }
      );
    } else {
      const dataPath = `${listType}List[${index}]`;
      this.setData({ [dataPath]: updatedItem });
    }
  },

  recalculateCounts() {
    this.setData({
      onSaleCount: this.data.onSaleList.length,
      offShelfCount: this.data.offShelfList.length,
      violationCount: this.data.violationList.length,
    });
  },

  onImagePreview(event: WechatMiniprogram.CustomEvent) {
    const { current, urls } = event.currentTarget.dataset;
    wx.previewImage({ current, urls });
  },
});
